<template>
  <!-- 车辆维保 -->
  <base-breadcrumb :title="$route.meta.title">
    <!-- 搜索 -->
    <searchData ref="searchData" :search-data="searchArr" @search="search" />
    <!-- 表格 -->
    <a-card :bordered="false">
      <!-- <title-name :title="$route.meta.title" /> -->
      <!-- <div class="mb12"> -->
      <!-- v-if="
            post.code !== 'PDAZR' &&
            post.code !== 'BCAZR' &&
            post.code !== 'COAZR' &&
            post.code !== 'BCACLGL' &&
            post.code !== 'COACLGL'
          " -->

      <!-- 导出 -->
      <!-- v-if="
            post.code === 'PDAZR' ||
            post.code === 'BCAZR' ||
            post.code === 'COAZR' ||
            post.code === 'BCACLGL' ||
            post.code === 'COACLGL'
          " -->
      <!-- <excel
          ref="exportAll"
          v-btnPermission="'oa_014_exp_03'"
          class="ml12"
          :file-name="`${post.name}_车辆维护申请`"
          is-click-generate="false"
        >
          <a-button
            slot="excelBtn"
            type="primary"
            icon="download"
            :loading="loading"
            @click="exportAll"
          >
            导出
          </a-button>
        </excel> -->
      <!-- </div> -->
      <a-spin :spinning="spinning">
        <!-- 表格 -->
        <list-table ref="table" row-key="id" :columns="columns" :request="loadData" :alert="true" show-size-changer
          show-quick-jumper :export-permission="{ select: 'oa_014_exp_03', all: 'oa_014_exp_03' }"
          :export-config="{ use: true, select: `${post.name}_车辆维保台账`, all: `${post.name}_车辆维保台账` }"
          :statisticsConfig="{ use: true, temp: statisticsTemp }">
          <a-button slot="prefix" slot-scope="ref" v-btnPermission="'oa_014_add_02'" icon="plus" type="primary"
            @click="handleManage(2)">
            维保申请
          </a-button>
          <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span>
          <template slot="actions" slot-scope="text, record">
            <MoreButton>
              <a v-btnPermission="'oa_014_loo_01'" @click="handleManage(0, record)">查看</a>
              <!-- 编辑 -->
              <template v-if="record.status == '0' || record.status == '3'">
                <a @click="handleManage(1, record)">编辑</a>
              </template>
              <!-- 填写实际维保信息 -->
              <template v-if="record.status == '2' && !record.spend">
                <a @click="handleOpen(record)">填写维保</a>
              </template>
              <!-- 删除 -->
              <template v-if="record.status == '0'">
                <a class="del_btn" @click="handleRemove(record.id)">删除</a>
              </template>
              <!-- 打印 -->
              <template v-if="record.status == '2'">
                <BasePrintButton type="link" :innerSpinning="false"
                  :beforePrintFn="checkProjectRiskReturnPrint(record.id)" @getLoadedState="getLoadedState" />
              </template>
              <!-- 当状态为审批中 -->
              <template v-if="record.status != '0'">
                <a @click="$bus.$emit('showApprovalDetailsDialog', record.id)">审批信息</a>
              </template>
            </MoreButton>
          </template>
          <!-- 状态 -->
          <template slot="status" slot-scope="text, record">
            <status-display :status-code="record.status" is-approval />
          </template>
        </list-table>
      </a-spin>
    </a-card>
    <!-- 表单弹窗 -->
    <dialog-form ref="dialogForm" :visible.sync="visible" edit-model="E" :form="form" :forms.sync="forms"
      header-title="维保信息" :width="1000" :rules="rules" :form-list="formList" @confirm="submitForm"
      @beforeClose="init = false">
      <!-- 维保明细清单及发票 -->
      <template #fileInfoVOS>
        <div class="file_item">
          <l-table :file-auto-loading="false" business-code="OF12" :upload-arrys.sync="forms.fileInfoVOS" />
          <div>支持格式：.rar .zip .doc .docx .pdf .jpg...</div>
        </div>
      </template>
      <template #formFooter>
        <a-divider />
        <title-name title="维保申请信息" />
        <custom-form is-validate :form-list="baseForm" :form="form" edit-model="V" />
      </template>
    </dialog-form>
  </base-breadcrumb>
</template>

<script>
// import { STable } from '@/components' // 表格
import { carMaintenanceApplication } from '@/api/office/vehicle/config' // api
import Selector from '@/components/Select/Selector'
import SelectCompanyAndProject from '@/components/Select/SelectCompanyAndProject' // 申请单位
import DialogForm from '@/components/DialogForm' // 弹窗
import StatusDisplay from '@/components/StatusDisplay'
import OrgTreeSelect from '@/components/OrgTreeSelect'
import BasePage from '@/views/basePage' // 基础配置
import BasePrintButton from '@/components/BasePrintButton' // 打印按钮

const searchArr = [
  // 搜索框
  {
    name: '申请单位',
    valueKey: 'searchQuery',
    type: OrgTreeSelect,
    attr: {
      isAutoSelectFirst: true
    }
  },
  // {
  //   name: '申请单位',
  //   valueKey: 'unitId',
  //   type: SelectCompanyAndProject
  // },
  {
    valueKey: 'typeId',
    name: '维保类型',
    type: Selector,
    selectType: '23',
    urlType: 'union'
  },
  {
    name: '车牌号',
    type: 'input',
    value: 'carNumber'
  },
  {
    name: '状态',
    value: 'status',
    type: 'select',
    data: [
      {
        value: '0',
        label: '待提交审批'
      },
      {
        value: '1',
        label: '审批中'
      },
      {
        value: '2',
        label: '审批通过'
      },
      {
        value: '3',
        label: '审批不通过'
      }
    ]
  },
  {
    name: '维保日期',
    type: 'dateRange',
    value: 'time',
    attr: {
      rangeFormat: ['startTime', 'endTime']
    }
  }
]
const columns = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    scopedSlots: { customRender: 'index' }
  },
  {
    title: '申请单位',
    ellipsis: true,
    dataIndex: 'carInfo.unitName'
  },
  {
    title: '申请人',
    ellipsis: true,
    dataIndex: 'driverName'
  },
  {
    title: '车牌号',
    ellipsis: true,
    dataIndex: 'carInfo.carNumber'
  },
  {
    title: '维保类型',
    ellipsis: true,
    dataIndex: 'typeName'
  },
  {
    title: '申请维保项目',
    ellipsis: true,
    width: 300,
    dataIndex: 'protectProject'
  },
  {
    title: '维保公里数（km）',
    dataIndex: 'preKilometre'
  },
  {
    title: '预计费用（元）',
    dataIndex: 'budget'
  },
  {
    title: '申请时间',
    ellipsis: true,
    dataIndex: 'createTime'
  },
  {
    title: '实际维保费用(元)',
    dataIndex: 'spend',
    customRender() {
      return arguments[0] || '—'
    }
  },
  {
    title: '维保时间',
    dataIndex: 'realTime',
    customRender() {
      return arguments[0] || '—'
    }
  },
  {
    title: '状态',
    dataIndex: 'status',
    // fixed: 'right',
    align: 'center',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    dataIndex: 'actions',
    width: '260px',
    fixed: 'right',
    align: 'center',
    scopedSlots: { customRender: 'actions' }
  }
]
export default {
  name: 'a' + Date.now(),
  extends: new BasePage(),
  components: {
    // STable,
    StatusDisplay,
    DialogForm,
    BasePrintButton,
  },
  data() {
    this.columns = columns
    this.searchArr = searchArr
    return {
      spinning: false,//打印loadding
      loading: false, // 导出loading
      queryParam: {}, // 查询参数
      loadData: (parameter) => {
        // if (!this.initFlag) {
        //   return false
        // }
        this.getSummary()
        const requestParameters = Object.assign({}, parameter, { query: this.queryParam })
        return carMaintenanceApplication.getList(requestParameters).then((res) => {
          if (res.data) {
            res.data.forEach((item) => {
              if (item.carInfo?.carNumber) {
                item.carNumber = item.carInfo.carNumber
              }
            })
          }
          return res
        })
      }, // 加载数据方法 必须为 Promise 对象
      statusMap: {
        0: {
          label: '不可用',
          color: '#ff9900'
        },
        1: {
          label: '可用',
          color: '#00A854'
        }
      },
      summary: {}, // 统计
      form: {}, // 弹窗表单
      visible: false, // 弹窗控件
      removeApi: carMaintenanceApplication,
      init: false, // 弹窗初始化标识
      rules: {
        realKilometre: [{ required: true, message: '请输入维保时公里数（km）', trigger: 'change' }],
        spend: [{ required: true, message: '请输入实际维保费用（元）', trigger: 'change' }],
        realTime: [{ required: true, message: '请选择维保日期', trigger: 'change' }],
        fileInfoVOS: [{ type: 'array', required: true, message: '请上传维保明细清单及发票', trigger: 'blur' }]
      }, // 校验规则
      formList: [
        {
          keyName: 'spend',
          type: 'BaseInputNumber',
          label: '实际维保费用（元）',
          span: 12,
          precision: 2,
          attrs: {
            min: 0
          }
        },
        {
          keyName: 'realTime',
          type: 'a-date-picker',
          label: '维保日期',
          span: 12,
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'realKilometre',
          type: 'BaseInputNumber',
          label: '维保时公里数（km）',
          span: 12,
          precision: 2,
          attrs: {
            min: 0
          }
        },
        {
          slot: true,
          keyName: 'fileInfoVOS',
          label: '维保明细清单及发票',
          span: 12
        }
      ], // 弹窗表单
      baseForm: [
        {
          keyName: 'carNumber',
          label: '维保车辆',
          span: 24
        },
        {
          keyName: 'typeName',
          label: '维保类型',
          span: 24
        },
        {
          keyName: 'protectProject',
          label: '维保项目',
          span: 24
        }
      ], // 弹窗基础信息表单
      forms: {}, // 弹窗回调表单
      // initFlag: false,
      post: {} //当前岗位
    }
  },
  mounted() {
    // 获取当前岗位
    this.post = this.$currentPost()
    // this.$refs.exportAll.tableToExcelFile(this.$refs.table, 0)
    this.$refs.searchData.form.setFieldsValue({
      // unitId: this.post?.id,
      // searchQuery: {
      //   _checked: this.$currentPost()?.id
      // }
    })
    this.queryParam = {
      // unitId: this.post?.id,
      // searchQuery: {
      //   _checked: this.$currentPost()?.id
      // }
    }
    // this.initFlag = true
    this.search()
  },
  watch: {
    // 监听附件实现附件校验
    'forms.fileInfoVOS': {
      immediate: true,
      handler() {
        if (this.init) {
          this.$nextTick(() => {
            this.$refs?.dialogForm.$refs.ruleForm?.validateField('fileInfoVOS')
          })
        }
      }
    }
  },
  methods: {
    checkProjectRiskReturnPrint(id) {
      return () => {
        return carMaintenanceApplication.print({ id: id }).then((res) => {
          return res.data.content
        })
      }
    },
    /**
     * 填写实际维保信息
     */
    handleOpen(record) {
      this.form = this.$clone(record)
      this.visible = true
      setTimeout(() => {
        this.init = true
      }, 500)
    },
    statisticsTemp() {
      return (
        <span>
          <span>总实际维保费用：<a>{this.summary.spendMoney || 0}</a></span>
        </span>
      )
    },
    /**
     * 统计
     */
    getSummary() {
      carMaintenanceApplication
        .statistics(Object.assign({}, { needCount: false, query: this.queryParam }))
        .then((res) => {
          if (res.data) {
            this.summary = res.data
          }
        })
    },
    /**
     * 导出
     */
    exportAll() {
      this.loading = true
      let form = this.$refs.searchData.form.getFieldsValue()
      if (form.time) {
        form.startTime = this.$dateFormat(form.time[0], 'D')
        form.endTime = this.$dateFormat(form.time[1], 'D')
        delete form.time
      }
      carMaintenanceApplication
        .getAllList(Object.assign({}, form))
        .then((res) => {
          this.loading = false
          if (res.data?.length > 0) {
            res.data.forEach((item, index) => {
              item.index = index + 1
              item.status = ['待提交审批', '审批中', '审批通过', '审批不通过'][item.status]
            })
            this.$refs.exportAll.setDataAndGenerate(res.data)
            this.$message.success('导出成功')
          } else {
            this.$message.warning('没有数据可以导出')
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    /**
     * 搜索
     */
    search(value) {
      value && (this.queryParam = value)
      this.$refs.table.refresh(true)
    },
    /**
     * 操作栏
     */
    handleManage(type, record) {
      let query = {
        editModel: type
      }
      if (record && record.id) {
        query.id = record.id
      }
      this.$router.push({
        name: '/vehicle/carMaintenanceEdit',
        query
      })
    },
    /**
     * 提交维保表单
     */
    submitForm(e) {
      // 格式化文件参数
      this.$confirm({
        title: '温馨提示',
        content: '请确认是否要提交，提交后不可修改',
        onOk: () => {
          e.fileId = e.fileInfoVOS?.map((item) => item.commonId)?.join()
          return carMaintenanceApplication.update(e).then(() => {
            this.$message.success('提交成功！')
            this.$refs.table.refresh(true)
            this.visible = false
          })
        }
      })
    },
    /**
 * 点击打印按钮主界面loadding
 */
    getLoadedState(val) {
      this.spinning = val;
    }
  }
}
</script>

<style lang="less" scoped>
.file_item {
  margin-top: -3px;
}

/deep/.ant-form-item {
  .ant-form-item-label {
    height: 28px;
    width: 180px;
    line-height: 22px;
    padding: 6px 4px 0 0;
    text-align: right;
    white-space: pre-wrap;
    overflow: visible;
  }

  .ant-form-item-control-wrapper {
    width: calc(100% - 180px);
  }
}
</style>
